﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using Resto.CostControl.Core;
using Resto.CostControl.Core.DWZAdapter;
using EfSearchModel.Model;
using Resto.CostControl.Core.Services;

namespace Resto.CostControl.Web.Controllers
{
    public class SemiMaterialStorageController : Controller
    {
        private readonly IRepository<MaterialProcess> _Repo;
        private readonly IRepository<MaterialProcessItem> _RepoItem;
        private readonly IRepository<Storage> _RepoStorage;
        private readonly IUnitOfWork _UnitOfWork;

        public SemiMaterialStorageController(
            IRepository<MaterialProcess> repo,
            IRepository<MaterialProcessItem> repoItem,
            IRepository<Storage> repoStorage,
            UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoItem;
            _RepoStorage = repoStorage;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index(DWZPageInfo pageInfo, QueryModel where)
        {
            var list = _Repo.GetPageable(pageInfo, where);

            ViewBag.Total = list.Total;
            ViewBag.PageNum = pageInfo.PageIndex + 1;
            ViewBag.NumPerPage = pageInfo.PageSize;
            ViewBag.OrderField = pageInfo.SortName;
            ViewBag.OrderDirection = pageInfo.SortOrder;
            ViewBag.Keywords = pageInfo.Keywords;
            ViewBag.SearchData = pageInfo.SearchData;

            return View(list.Page);
        }

        public ActionResult Edit(string Id)
        {
            MaterialProcess data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
                data.Items = _RepoItem.FindAll(m => m.OrderId == Id).ToList();
            }
            else
            {
                data = new MaterialProcess();
                data.Items = new List<MaterialProcessItem>();

                data.ProcessDate = DateTime.Now;
                data.OrderState = "草稿";
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialProcess data, IList<MaterialProcessItem> items)
        {

            if (ModelState.IsValid)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(data.Id))
                    {
                        data.Id = Guid.NewGuid().ToString();
                        _Repo.Insert(data);
                    }
                    else
                    {
                        data = _Repo.Find(data.Id);
                        TryUpdateModel(data);

                        _RepoItem.DeleteAll(m => m.OrderId == data.Id);
                    }

                    if (items != null)
                    {
                        foreach (var m in items)
                        {
                            var item = new MaterialProcessItem
                            {
                                Id = Guid.NewGuid().ToString(),
                                OrderId = data.Id,
                                MaterialId = m.Id,
                                Category = m.Category,
                                Code = m.Code,
                                Name = m.Name,
                                ActualPickCount = m.ActualPickCount,
                                ActualStorageCount = m.ActualStorageCount,
                                ExpectedPickCount = m.ExpectedPickCount,
                                ExpectedStorageCount = m.ExpectedStorageCount
                            };
                            _RepoItem.Insert(item);

                            if (data.ItemDesc.IndexOf(item.Name) < 0)
                            {
                                data.ItemDesc += string.Format("{0}（{1}g），", item.Name, item.ExpectedPickCount);
                            }

                            // 更新库存
                            var storage = _RepoStorage.Find(s => s.MaterialId == item.MaterialId);
                            if (storage == null)
                            {
                                storage = new Storage();
                                storage.Id = Guid.NewGuid().ToString();
                                _RepoStorage.Insert(storage);
                            }

                            storage.MaterialId = item.MaterialId;
                            storage.Category = item.Category;
                            storage.Type = "SemiMaterial";
                            storage.Code = item.Code;
                            storage.Name = item.Name;
                            //storage.CurrentPrice = item.Price;
                            storage.ActualSorage += item.ActualStorageCount;
                        }
                    }
                    data.ItemDesc = data.ItemDesc.TrimEnd('，');

                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new FormReturnJson
            {
                statusCode = "200",
                message = "操作成功",
                navTabId = "SemiMaterialPick",
                callbackType = "closeCurrent",
                forwardUrl = "",
            };
            return Json(result);
        }
    }
}
